import { type BaseRequest } from '@/types/request'
import { useUserStore } from '@/store/user'

const baseUrl = 'http://172.18.0.115:6060/api'

const { getIsLogin, getToken } = useUserStore()
const isLogin = getIsLogin()

function buildQueryString(params?: Record<string, any>) {
  if (!params) return ''
  const query = Object.keys(params)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')
  return query ? `?${query}` : ''
}

async function request<T = any>(config: BaseRequest): Promise<T> {
  const query = buildQueryString(config.params)
  try {
    const res = await uni.request({
      url: baseUrl + config.url + query,
      method: config.method,
      data: config.data,
      header: {
        content: 'application/json',
        token: void 0
      }
    })
    return res.data as T
  } catch (e) {
    uni.showToast({ title: JSON.stringify(e) })
    return Promise.reject(e)
  }
}

uni.addInterceptor('request', {
  invoke: (args) => {
    // 请求拦截操作
    if (isLogin) {
      args.header.token = getToken()
    }
    return args
  },
  success: (args) => {
    // 响应拦截操作

    return args
  }
})

const api = {
  get<T>(config: BaseRequest): Promise<T> {
    return request({ ...config, method: 'GET' })
  },
  post<T>(config: BaseRequest): Promise<T> {
    return request({ ...config, method: 'POST' })
  },
  put<T>(config: BaseRequest): Promise<T> {
    return request({ ...config, method: 'PUT' })
  },
  del<T>(config: BaseRequest): Promise<T> {
    return request({ ...config, method: 'DELETE' })
  },
  request<T>(config: BaseRequest): Promise<T> {
    return request({ ...config })
  }
}

export default api
